<template>
  <div class="marketing-statistics">
    <!-- 时间筛选 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="统计时间">
          <el-date-picker
            v-model="filterForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcuts"
            @change="handleTimeRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据概览 -->
    <div class="statistics-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="overview-card">
            <template #header>
              <div class="card-header">
                <span>活动总数</span>
                <el-tag size="small" :type="overviewData.activityCount.trend > 0 ? 'success' : 'danger'">
                  {{ overviewData.activityCount.trend > 0 ? '↑' : '↓' }}
                  {{ Math.abs(overviewData.activityCount.trend) }}%
                </el-tag>
              </div>
            </template>
            <div class="card-value">{{ overviewData.activityCount.value }}</div>
            <div class="card-footer">
              <span>进行中：{{ overviewData.activityCount.ongoing }}</span>
              <span>已结束：{{ overviewData.activityCount.ended }}</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="overview-card">
            <template #header>
              <div class="card-header">
                <span>优惠券总数</span>
                <el-tag size="small" :type="overviewData.couponCount.trend > 0 ? 'success' : 'danger'">
                  {{ overviewData.couponCount.trend > 0 ? '↑' : '↓' }}
                  {{ Math.abs(overviewData.couponCount.trend) }}%
                </el-tag>
              </div>
            </template>
            <div class="card-value">{{ overviewData.couponCount.value }}</div>
            <div class="card-footer">
              <span>已发放：{{ overviewData.couponCount.issued }}</span>
              <span>已使用：{{ overviewData.couponCount.used }}</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="overview-card">
            <template #header>
              <div class="card-header">
                <span>营销订单数</span>
                <el-tag size="small" :type="overviewData.orderCount.trend > 0 ? 'success' : 'danger'">
                  {{ overviewData.orderCount.trend > 0 ? '↑' : '↓' }}
                  {{ Math.abs(overviewData.orderCount.trend) }}%
                </el-tag>
              </div>
            </template>
            <div class="card-value">{{ overviewData.orderCount.value }}</div>
            <div class="card-footer">
              <span>活动订单：{{ overviewData.orderCount.activity }}</span>
              <span>优惠券订单：{{ overviewData.orderCount.coupon }}</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="overview-card">
            <template #header>
              <div class="card-header">
                <span>营销销售额</span>
                <el-tag size="small" :type="overviewData.salesAmount.trend > 0 ? 'success' : 'danger'">
                  {{ overviewData.salesAmount.trend > 0 ? '↑' : '↓' }}
                  {{ Math.abs(overviewData.salesAmount.trend) }}%
                </el-tag>
              </div>
            </template>
            <div class="card-value">¥{{ overviewData.salesAmount.value }}</div>
            <div class="card-footer">
              <span>活动销售额：¥{{ overviewData.salesAmount.activity }}</span>
              <span>优惠券销售额：¥{{ overviewData.salesAmount.coupon }}</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 趋势图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>营销订单趋势</span>
              <el-radio-group v-model="orderTrendType" size="small">
                <el-radio-button label="day">日</el-radio-button>
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="orderTrendChartRef" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>营销销售额趋势</span>
              <el-radio-group v-model="salesTrendType" size="small">
                <el-radio-button label="day">日</el-radio-button>
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="salesTrendChartRef" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 活动效果分析 -->
    <el-card class="analysis-card">
      <template #header>
        <div class="card-header">
          <span>活动效果分析</span>
          <el-button type="primary" link @click="handleExportActivityData">
            导出数据
          </el-button>
        </div>
      </template>
      <el-table :data="activityAnalysis" border style="width: 100%">
        <el-table-column prop="name" label="活动名称" min-width="150" />
        <el-table-column prop="type" label="活动类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getActivityTypeTag(row.type)">
              {{ getActivityTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getActivityStatusTag(row.status)">
              {{ getActivityStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="participantCount" label="参与人数" width="120" />
        <el-table-column prop="orderCount" label="订单数" width="120" />
        <el-table-column prop="salesAmount" label="销售额" width="150">
          <template #default="{ row }">
            ¥{{ row.salesAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="conversionRate" label="转化率" width="120">
          <template #default="{ row }">
            {{ row.conversionRate }}%
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewActivityDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="activityPage.current"
          v-model:page-size="activityPage.size"
          :total="activityPage.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleActivityPageSizeChange"
          @current-change="handleActivityPageChange"
        />
      </div>
    </el-card>

    <!-- 优惠券效果分析 -->
    <el-card class="analysis-card">
      <template #header>
        <div class="card-header">
          <span>优惠券效果分析</span>
          <el-button type="primary" link @click="handleExportCouponData">
            导出数据
          </el-button>
        </div>
      </template>
      <el-table :data="couponAnalysis" border style="width: 100%">
        <el-table-column prop="name" label="优惠券名称" min-width="150" />
        <el-table-column prop="type" label="优惠券类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getCouponTypeTag(row.type)">
              {{ getCouponTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getCouponStatusTag(row.status)">
              {{ getCouponStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="issuedCount" label="发放数量" width="120" />
        <el-table-column prop="usedCount" label="使用数量" width="120" />
        <el-table-column prop="usageRate" label="使用率" width="120">
          <template #default="{ row }">
            {{ row.usageRate }}%
          </template>
        </el-table-column>
        <el-table-column prop="orderCount" label="带动订单" width="120" />
        <el-table-column prop="salesAmount" label="带动销售额" width="150">
          <template #default="{ row }">
            ¥{{ row.salesAmount }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewCouponDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="couponPage.current"
          v-model:page-size="couponPage.size"
          :total="couponPage.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleCouponPageSizeChange"
          @current-change="handleCouponPageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import {
  getMerchantMarketingOverview,
  getMerchantMarketingTrend,
  getMerchantActivityAnalysis,
  getMerchantCouponAnalysis,
  exportMerchantActivityData,
  exportMerchantCouponData
} from '@/api/merchant'

const router = useRouter()

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 筛选表单
const filterForm = reactive({
  timeRange: [
    dayjs().subtract(30, 'day').toDate(),
    dayjs().toDate()
  ]
})

// 数据概览
const overviewData = reactive({
  activityCount: {
    value: 0,
    trend: 0,
    ongoing: 0,
    ended: 0
  },
  couponCount: {
    value: 0,
    trend: 0,
    issued: 0,
    used: 0
  },
  orderCount: {
    value: 0,
    trend: 0,
    activity: 0,
    coupon: 0
  },
  salesAmount: {
    value: 0,
    trend: 0,
    activity: 0,
    coupon: 0
  }
})

// 趋势图表
const orderTrendChartRef = ref(null)
const salesTrendChartRef = ref(null)
let orderTrendChart = null
let salesTrendChart = null
const orderTrendType = ref('day')
const salesTrendType = ref('day')

// 活动分析
const activityAnalysis = ref([])
const activityPage = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 优惠券分析
const couponAnalysis = ref([])
const couponPage = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取数据概览
const getOverviewData = async () => {
  try {
    const [startDate, endDate] = filterForm.timeRange
    const params = {
      startDate: dayjs(startDate).format('YYYY-MM-DD'),
      endDate: dayjs(endDate).format('YYYY-MM-DD')
    }
    const { data } = await getMerchantMarketingOverview(params)
    Object.assign(overviewData, data)
  } catch (error) {
    console.error('获取数据概览失败:', error)
    ElMessage.error('获取数据概览失败')
  }
}

// 获取趋势数据
const getTrendData = async () => {
  try {
    const [startDate, endDate] = filterForm.timeRange
    const params = {
      startDate: dayjs(startDate).format('YYYY-MM-DD'),
      endDate: dayjs(endDate).format('YYYY-MM-DD'),
      orderType: orderTrendType.value,
      salesType: salesTrendType.value
    }
    const { data } = await getMerchantMarketingTrend(params)
    updateOrderTrendChart(data.orderTrend)
    updateSalesTrendChart(data.salesTrend)
  } catch (error) {
    console.error('获取趋势数据失败:', error)
    ElMessage.error('获取趋势数据失败')
  }
}

// 更新订单趋势图表
const updateOrderTrendChart = (data) => {
  if (!orderTrendChart) return
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['活动订单', '优惠券订单', '总订单']
    },
    xAxis: {
      type: 'category',
      data: data.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '活动订单',
        type: 'line',
        data: data.activityOrders
      },
      {
        name: '优惠券订单',
        type: 'line',
        data: data.couponOrders
      },
      {
        name: '总订单',
        type: 'line',
        data: data.totalOrders
      }
    ]
  }
  orderTrendChart.setOption(option)
}

// 更新销售额趋势图表
const updateSalesTrendChart = (data) => {
  if (!salesTrendChart) return
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        return params.map(param => {
          return `${param.seriesName}: ¥${param.value}`
        }).join('<br/>')
      }
    },
    legend: {
      data: ['活动销售额', '优惠券销售额', '总销售额']
    },
    xAxis: {
      type: 'category',
      data: data.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '活动销售额',
        type: 'line',
        data: data.activitySales
      },
      {
        name: '优惠券销售额',
        type: 'line',
        data: data.couponSales
      },
      {
        name: '总销售额',
        type: 'line',
        data: data.totalSales
      }
    ]
  }
  salesTrendChart.setOption(option)
}

// 获取活动分析数据
const getActivityAnalysis = async () => {
  try {
    const [startDate, endDate] = filterForm.timeRange
    const params = {
      startDate: dayjs(startDate).format('YYYY-MM-DD'),
      endDate: dayjs(endDate).format('YYYY-MM-DD'),
      page: activityPage.current,
      size: activityPage.size
    }
    const { data } = await getMerchantActivityAnalysis(params)
    activityAnalysis.value = data.list
    activityPage.total = data.total
  } catch (error) {
    console.error('获取活动分析数据失败:', error)
    ElMessage.error('获取活动分析数据失败')
  }
}

// 获取优惠券分析数据
const getCouponAnalysis = async () => {
  try {
    const [startDate, endDate] = filterForm.timeRange
    const params = {
      startDate: dayjs(startDate).format('YYYY-MM-DD'),
      endDate: dayjs(endDate).format('YYYY-MM-DD'),
      page: couponPage.current,
      size: couponPage.size
    }
    const { data } = await getMerchantCouponAnalysis(params)
    couponAnalysis.value = data.list
    couponPage.total = data.total
  } catch (error) {
    console.error('获取优惠券分析数据失败:', error)
    ElMessage.error('获取优惠券分析数据失败')
  }
}

// 导出活动数据
const handleExportActivityData = async () => {
  try {
    const [startDate, endDate] = filterForm.timeRange
    const params = {
      startDate: dayjs(startDate).format('YYYY-MM-DD'),
      endDate: dayjs(endDate).format('YYYY-MM-DD')
    }
    await exportMerchantActivityData(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出活动数据失败:', error)
    ElMessage.error('导出活动数据失败')
  }
}

// 导出优惠券数据
const handleExportCouponData = async () => {
  try {
    const [startDate, endDate] = filterForm.timeRange
    const params = {
      startDate: dayjs(startDate).format('YYYY-MM-DD'),
      endDate: dayjs(endDate).format('YYYY-MM-DD')
    }
    await exportMerchantCouponData(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出优惠券数据失败:', error)
    ElMessage.error('导出优惠券数据失败')
  }
}

// 查看活动详情
const handleViewActivityDetail = (row) => {
  router.push(`/merchant/marketing/detail/${row.id}`)
}

// 查看优惠券详情
const handleViewCouponDetail = (row) => {
  router.push(`/merchant/marketing/coupon-detail/${row.id}`)
}

// 活动类型标签
const getActivityTypeTag = (type) => {
  const map = {
    discount: 'success',
    seckill: 'danger',
    group: 'warning',
    new_user: 'info'
  }
  return map[type] || 'info'
}

const getActivityTypeLabel = (type) => {
  const map = {
    discount: '满减活动',
    seckill: '秒杀活动',
    group: '拼团活动',
    new_user: '新人专享'
  }
  return map[type] || type
}

// 活动状态标签
const getActivityStatusTag = (status) => {
  const map = {
    not_started: 'info',
    ongoing: 'success',
    ended: 'danger'
  }
  return map[status] || 'info'
}

const getActivityStatusLabel = (status) => {
  const map = {
    not_started: '未开始',
    ongoing: '进行中',
    ended: '已结束'
  }
  return map[status] || status
}

// 优惠券类型标签
const getCouponTypeTag = (type) => {
  const map = {
    discount: 'success',
    amount: 'warning'
  }
  return map[type] || 'info'
}

const getCouponTypeLabel = (type) => {
  const map = {
    discount: '折扣券',
    amount: '满减券'
  }
  return map[type] || type
}

// 优惠券状态标签
const getCouponStatusTag = (status) => {
  const map = {
    not_started: 'info',
    ongoing: 'success',
    ended: 'danger'
  }
  return map[status] || 'info'
}

const getCouponStatusLabel = (status) => {
  const map = {
    not_started: '未开始',
    ongoing: '进行中',
    ended: '已结束'
  }
  return map[status] || status
}

// 时间范围变化
const handleTimeRangeChange = () => {
  getOverviewData()
  getTrendData()
  getActivityAnalysis()
  getCouponAnalysis()
}

// 搜索
const handleSearch = () => {
  getOverviewData()
  getTrendData()
  getActivityAnalysis()
  getCouponAnalysis()
}

// 重置
const handleReset = () => {
  filterForm.timeRange = [
    dayjs().subtract(30, 'day').toDate(),
    dayjs().toDate()
  ]
  handleSearch()
}

// 活动分页
const handleActivityPageSizeChange = (val) => {
  activityPage.size = val
  getActivityAnalysis()
}

const handleActivityPageChange = (val) => {
  activityPage.current = val
  getActivityAnalysis()
}

// 优惠券分页
const handleCouponPageSizeChange = (val) => {
  couponPage.size = val
  getCouponAnalysis()
}

const handleCouponPageChange = (val) => {
  couponPage.current = val
  getCouponAnalysis()
}

// 监听趋势类型变化
watch(orderTrendType, () => {
  getTrendData()
})

watch(salesTrendType, () => {
  getTrendData()
})

// 初始化图表
const initCharts = () => {
  orderTrendChart = echarts.init(orderTrendChartRef.value)
  salesTrendChart = echarts.init(salesTrendChartRef.value)
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小变化
const handleResize = () => {
  orderTrendChart?.resize()
  salesTrendChart?.resize()
}

onMounted(() => {
  initCharts()
  getOverviewData()
  getTrendData()
  getActivityAnalysis()
  getCouponAnalysis()
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  orderTrendChart?.dispose()
  salesTrendChart?.dispose()
})
</script>

<style lang="scss" scoped>
.marketing-statistics {
  padding: 20px;

  .filter-card {
    margin-bottom: 20px;
  }

  .statistics-overview {
    margin-bottom: 20px;

    .overview-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .card-value {
        font-size: 24px;
        font-weight: bold;
        margin: 10px 0;
      }

      .card-footer {
        display: flex;
        justify-content: space-between;
        color: var(--el-text-color-secondary);
        font-size: 14px;
      }
    }
  }

  .chart-row {
    margin-bottom: 20px;

    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .chart {
        height: 400px;
      }
    }
  }

  .analysis-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 